//
//  PhotoBrowserViewController.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/5/21.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit

private let cellIdentifier = "PhotoCellIdentifier"

class PhotoBrowserViewController: UIViewController,  UICollectionViewDataSource {

  /// 所有图像的数组
    var imageURLs: [NSURL]?
  /// 选中照片索引
    var selectedIndex: Int = 0 {
        didSet {
            println("设置照片索引 \(selectedIndex)")
        }
    }
    ///collection 的布局
    lazy var layout: UICollectionViewFlowLayout = {
      let l = UICollectionViewFlowLayout()
      
        l.itemSize = self.view.bounds.size
        l.minimumInteritemSpacing = 0
        l.minimumLineSpacing = 0
        l.scrollDirection = UICollectionViewScrollDirection.Horizontal
        return l
     }()
    /// 创建collectionView
    lazy var collectionView: UICollectionView = {
      let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout:self.layout)
       cv.dataSource = self
        //分页
        cv.pagingEnabled = true
        return cv
    }()
    
    //初始化界面
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collectionView)
        let closeBtn = createButton("关闭")
       
         closeBtn.addTarget(self, action: "closeBtn", forControlEvents: UIControlEvents.TouchUpInside)
      
        let saveBtn = createButton("保存")
        saveBtn.addTarget(self, action: "saveBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 2. 自动布局的类函数 NSLayoutConstraint
        // constraintsWithVisualFormat返回的是约束的数组
        // 1> VLF 语言
        var cons = [AnyObject]()
        //将生成的约束追加到临时数组中
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[closeBtn(80)]-8-[saveBtn(80)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn, "saveBtn": saveBtn])
          cons += NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn": closeBtn])
        
        /**
        任意一个控件，都可以参照另外一个控件，设置准确的位置属性
        
        参数
        1. 要设置约束的控件
        2. 约束属性
        3. 参照控件的关系
        4. 参照哪一个控件
        5. 被参照的约束属性
        6. 参照的乘积
        7. 约束数值
        */
        cons.append(NSLayoutConstraint(item: saveBtn, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: closeBtn, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        // 2.添加约束
        view.addConstraints(cons)
    }
    
    ///关闭视图
    func closeBtn() {
     dismissViewControllerAnimated(true, completion: nil)
     
    }
    
    ///保存按钮
    func saveBtn() {
     println(__FUNCTION__)
    
    }
    ///创建button
    private func createButton(title: String) -> UIButton {
     let btn = UIButton()
       btn.setTitle(title, forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.brownColor()
        view.addSubview(btn)
        //取消 autoresizing 转换标记
        btn.setTranslatesAutoresizingMaskIntoConstraints(false)
        return btn
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: cellIdentifier)
    }
    
   // MARK: - 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        println("count---> \(self.imageURLs?.count)")
        
        return self.imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 如果没有在缓冲区找到可用的 cell，会调用默认的构造函数 initWithFrame
        // 创建一个 cell，同时会把 layout 的 itemSize 传递进方法
        // 对比：storyboard为什么不能有准确的 frame？
        // 原因：sb 开发时，原型cell是在 sb 中创建的，查询可重用 cell，一定会拿到一个 cell
        // 因此，不会再调用 cell 的默认构造函数！
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.backgroundColor = UIColor(red: rndColor(), green: rndColor(), blue: rndColor(), alpha: 1.0)
        cell.imageURL = imageURLs![indexPath.item]
        // 一定要添加自控制器
        if !(childViewControllers as NSArray).containsObject(cell.viewerVC!)
        {
         addChildViewController(cell.viewerVC!)
        }
        
        return cell
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        println(__FUNCTION__)
        
        scrollToIndex()
    }
    
    func rndColor() -> CGFloat {
        return CGFloat(arc4random_uniform(256)) / 255
    }
    
    ///滚动到指定索引
    private func scrollToIndex(){
     
        let path = NSIndexPath(forItem: selectedIndex, inSection: 0)
     
        collectionView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    
}

class PhotoBrowserCell: UICollectionViewCell {

  ///查看照片控制器
    var viewerVC: PhotoViewerViewController?
    
    ///要显示的图片的 url
    var imageURL: NSURL? {
        didSet {
         viewerVC?.imageURL = imageURL
        }
    }
   
   override init(frame: CGRect) {
        super.init(frame: frame)
    // frame 已经是 cell 真正的大小，原因在于 layout
     println("\(__FUNCTION__) \(frame)")
    
     viewerVC = PhotoViewerViewController()
    
    //添加视图
    viewerVC?.view.frame = bounds

    addSubview(viewerVC!.view)
    
    }
   
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}



